<?php
namespace app\lib\exception;

use think\exception\Handle;
use think\Request;
use think\Log;

/** 
* Document
*/
class ExceptionHandler extends Handle{
    
    private $httpCode;
    private $msg;
    private $errorCode;


    public function render(\Exception $e){
        // 判断是否为自定义异常
        if($e instanceof Base){
            $this->httpCode  = $e->httpCode;
            $this->msg       = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            // 开发模式下，返回thinkphp自带错误页面
            if(config('app_debug')) return parent::render($e);
            $this->httpCode = 500;
            $this->msg = '服务器内部错误';
            $this->errorCode = 999;
            $this->recodeErrorLog($e);
        }
        $request = Request::instance();
        $res = [
            'msg' => $this->msg,
            'errorCode' => $this->errorCode,
            'data' =>[
                'requestUrl' => $request->url()
            ]
        ];
        return json($res,$this->httpCode);
    }

    public function recodeErrorLog(\Exception $e){
        Log::init([
            'type' => 'File',
            'path' => LOG_PATH,
            'level' => ['error']
        ]);
        Log::error($e->getMessage());
    }
}